package com.android.microweather;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

class CityListView extends RelativeLayout {
	public CityListView(Context context, City city) {
		super(context);
		
		ImageView forecastImage = new ImageView(context);
		if (city.getDays() != null && city.getDays().size() > 0) {
			try {
				forecastImage.setImageBitmap(Utils.createBitmap(context, city.getDays().get(0)));
			} catch (Exception e) {
				// Fallback plan: assign N/A image if there's nothing else to show.
				forecastImage.setImageResource(R.drawable.not_available);
			}
				
		}
		else
			forecastImage.setImageResource(R.drawable.not_available);
		forecastImage.setId(1);
		RelativeLayout.LayoutParams forecastImageParams =
			new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		forecastImageParams.setMargins(1, 1, 1, 1);
		forecastImageParams.addRule(ALIGN_PARENT_LEFT);
		addView(forecastImage, forecastImageParams);
		
		TextView cityName = new TextView(context);
		cityName.setText(city.getName());
		cityName.setTextSize(14f);
		cityName.setTextColor(Color.WHITE);
		cityName.setId(2);
		RelativeLayout.LayoutParams cityNameParams =
			new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		cityNameParams.addRule(RIGHT_OF, 1);
		addView(cityName, cityNameParams);
		
		ImageView statusImage = new ImageView(context);
		statusImage.setImageResource(R.drawable.icon);
		statusImage.setId(3);
		RelativeLayout.LayoutParams statusImageParams =
			new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		statusImageParams.addRule(ALIGN_PARENT_RIGHT);
		addView(statusImage, statusImageParams);
		}
}

public class CityListAdapter extends BaseAdapter {

	private Context		context;
	private List<City>	cityList;
	
	public CityListAdapter(Context context, List<City> cityList) {
		super();
		this.context = context;
		this.cityList = cityList;
	}

	@Override
	public int getCount() {
		return cityList.size();
	}

	@Override
	public Object getItem(int position) {
		return cityList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		City city = cityList.get(position);
		return new CityListView(this.context, city);
	}

}
